<template>
<div>
  <div class="headbox">
    <!-- 居中 -->
    <van-row class="head" type="flex" justify="center">
      <van-col span="18" style="display:flex;justify-content: center;">
        <van-uploader
          v-model="fileList"
          :accept="accept"
          :max-count="maxcount"
          :before-read="beforeRead"
          :after-read="afterRead"
          :max-size="maxsize"
          @oversize="onOversize"
        />
      </van-col>
    </van-row>


    <van-row type="flex" justify="center">
      <van-col span="10">
        <van-button
          v-show="!isresoving"
          @click="resolveimg"
          class="upbtn"
          color="linear-gradient(to right, #ff6034, #ee0a24)"
        >
          解析
        </van-button>
        <van-overlay :show="isresoving" >
          <div class="wrapper">
            <van-loading class="block"  color="#0094ff" />
          </div>
          
        </van-overlay>
        
      </van-col>
    </van-row>
  </div>

  <van-popup round  v-model="btnsaveshow" position="top" :style="{ height: '45%' }">
    <div class="fonttypepanel">
        <van-divider
          :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 16px' }"
        >
          保存类型
        </van-divider>
        <van-radio-group v-model="fonttype"  class="typescrolllist">
          <template v-for="item in fonttypelist" >
            <van-radio :name="item.id" :key="item.id">
            {{item.name}}
            <template #icon="props">
                <img class="img-icon" :src="props.checked ? activeIcon : inactiveIcon" />
            </template>
            </van-radio>
          </template>
        </van-radio-group>
      
        <van-field
          v-model="newtype"
          clearable
          placeholder="新增类型"
        >
          <template #button>
            <van-button  icon="plus" @click="addtype()" size="small" type="primary">新增</van-button>
            
          </template>
        </van-field>
        <van-button  class="btngroup" size="small" @click="btnsave()" color="#07c160">保存</van-button>
    </div>
  </van-popup>

  <van-row type="flex"  justify="center" v-if="fontdata.length>0">
      <van-col span="24">
        <van-divider>操作</van-divider>
        <van-sticky :offset-top="46">
          <div class="cpmOP">
          <van-button  size="small" @click="btnpop()" color="#07c160">保存</van-button>
          <van-button  size="small" @click="btnreset()" color="rgb(114, 50, 221)">重置</van-button>
          <van-button  size="small" @click="btnclean()" color="#ee0a24">清空</van-button>
        </div>
        </van-sticky>
          
      
      </van-col>
  </van-row>

  <div class="List" v-if="fontdata.length>0">
    <van-divider>列表</van-divider>
    <template v-for="item,index in opfontdata" >
      <div class="van-hairline--surround fontitem" :key="index+'|'+item+'|'+index">
      <van-field
      v-model="opfontdata[index]"
      autosize
      class="itemtext"
       type="textarea"
    >
    <template #left-icon>
        <van-tag color="#ffe1e1" text-color="#ad0000">段落{{index+1}}</van-tag>
    </template>
    
      <template #extra>
        <div class="fontOperation">
        <van-button @click="btntop(index)"  size="mini" type="primary">↑</van-button>
        <van-button  @click="btnbottom(index)"  size="mini" type="primary">↓</van-button>
        <van-button @click="btndel(index)"   size="mini" type="primary">-</van-button>
        <van-button @click="btnadd(index)"  size="mini" type="primary">+</van-button>
        <van-button  @click="btncopy(index)" size="mini" type="primary">copy</van-button>
        <van-button  @click="btnpaste(index)" size="mini" type="primary">paste</van-button>
        </div>
      </template>
      
    </van-field>

      </div>
      
    </template>


    
    
  </div>

</div>
  
</template>

<script>
import { Toast,Notify } from "vant";
import { img2font,savefont,getfonttype,addfonttype } from "@/api/mixin";
import { mapGetters } from "vuex";
import singleupload from "@/api/singleupload";
export default {
  name: "ToFont",
  data() {
    return {
      newtype:'',
      btnsaveshow:false,
      fonttype:'',
      activeIcon: require('@/assets/img/radiochoise.png'),
      inactiveIcon: require('@/assets/img/radiounchoise.png'),
      fonttypelist:[],
      fileList: [],
      sms:'',
      fontdata:[],
      opfontdata:[],
      log_id:'',
      isresoving:false,
      copydata:'',
      imgpath:'',
    };
  },
  created() {
    this.$store.dispatch("mixin/getFontToken");
  },
  computed: {
    ...mapGetters(["FontToken"]),
    resolved(){
      return this.fileList.length>0;
    },
  },
  props: {
    maxcount: {
      type: Number,
      default: 1,
    },
    maxsize: {
      type: String,
      default: "2*1024*1024",
    },
    accept: {
      type: String,
      default: "image/*",
    },
    // accept: {
    //   type: String,
    //   default:
    //     "image/*,video/*,audio/*,.pdf,.xls,.zip,.rar,.ppt,.pptx,.text,.csv,.xlsx,.doc,.docx",
    // },
  },
  methods: {
    //新增保存类型
    async addtype(){
      if(!this.newtype){
        Toast.fail('请输入类型名称');
        return
      }
      await addfonttype(this.newtype)
        .then(res=>{
          let data = res.data;
          console.log(data);
          data["date"] = new Date().Format("yyyy-MM-dd hh:mm:ss");
          this.fonttype = data["id"];
          this.fonttypelist.unshift(data);
          Toast.success('新增成功');
        })
        .catch(err=>{
          console.log(err);
        })
    },
    //点击保存按钮
    async btnpop(){
      getfonttype()
        .then(res=>{
          let data = res.data;
          
          this.fonttypelist=[];
          if(data.length>0){
            data.forEach(element => {
              let fonttypejson ={
                id:element.id,
                name:element.name,
                date:element.fmtdate
              }
              this.fonttypelist.push(fonttypejson);
            });
          }
          this.btnsaveshow = true;
        })
        .catch(err=>{
          console.log(err);
        })
      
    },
    btnsave(){
      console.log(this.fonttype);
      //保存笔记
      if(!this.imgpath){
        Toast.fail(`请先上传图片`);
        return
      }


      let content = '';//文本字符串
      this.opfontdata.forEach(element => {
        content+=element+'\n';
      });

      savefont(this.imgpath,content,this.fonttype)
        .then(data=>{
          Toast.success(data.message);
          this.btnsaveshow = false;
        })
        .catch(err=>{
          Toast.fail(err);
        })

    },
    btnreset(){
      this.opfontdata = this.fontdata.slice(0);
      
    },
    btnclean(){
      this.imgpath ='';
      this.fontdata.splice(0);
      this.opfontdata.splice(0);
      this.fileList = [];
      this.log_id='';
    },
    btntop(index){
      //将所选输入框内容添加到上一个输入框内
      if(index>0){
       let val =  this.opfontdata[index];
       this.opfontdata[index-1] = this.opfontdata[index-1]+''+val;
       this.opfontdata.splice(index,1);//删除原输入框
       Notify({
        type: 'success',
        message: '合并成功',
        duration: 500,
      });
      }
    },
    btnbottom(index){
      if(index<this.opfontdata.length-1){
       let val =  this.opfontdata[index];
       this.opfontdata[index+1] = val+''+this.opfontdata[index+1];
       this.opfontdata.splice(index,1);//删除原输入框
       Notify({
        type: 'success',
        message: '合并成功',
        duration: 500,
      });
      }
    },
    btndel(index){
      this.opfontdata.splice(index,1);//删除原输入框
      Notify({
        type: 'danger',
        message: '删除成功',
        duration: 500,
      });
    },
    btnadd(index){
      if(index<this.opfontdata.length-1){
        this.opfontdata.splice(index+1,0,'');
      }else{
        this.opfontdata.push('');
      }
      Notify({
        type: 'success',
        message: '添加成功',
        duration: 500,
      });
    },
    btncopy(index){
      this.copydata = this.opfontdata[index];
      Notify({
        type: 'success',
        message: '复制成功',
        duration: 500,
      });
    },
    btnpaste(index){
      this.opfontdata.splice(index,1,this.opfontdata[index].concat(this.copydata));
      
      Notify({
        type: 'success',
        message: '粘贴成功',
        duration: 500,
      });
    },
    async resolveimg(){
      if(this.fileList.length!=1){
        Toast.fail(`请先上传图片`);
        return
      }
      if(!this.imgpath){
        Toast.fail(`请先上传图片`);
        return
      }
      this.isresoving = true;
      let image = encodeURI(
        this.fileList[0].content.slice(this.fileList[0].content.indexOf("base64,") + 7)
      );
      //调用接口
      await img2font(image, this.FontToken)
        .then((res) => {
          let data = res.data;
          if(data.error_code){
            Toast.fail(`解析失败 ${data.error_msg}`);
          }else{
            this.log_id=data.log_id;
            let tempdata =  data.words_result;
            for(let i=0;i<tempdata.length;i++){
              this.fontdata[i] = tempdata[i].words;
            }

            this.opfontdata = this.fontdata.slice(0);//克隆
          }
        })
        .catch((err) => {
          Toast.fail(`解析失败 ${err}`);
        });

        this.isresoving = false;
    },
    beforeRead(file) {
      //上传之前校验
      if (!/^image\/.*$/.test(file.type)) {
        Toast("只允许上传图片！");
        return false;
      }
      return true;
    },
    afterRead(file) {
      file.status = 'uploading';
      file.message = '上传中...';
      
      //上传文件
       singleupload(file.file)
        .then((data) => {
          file.status = 'done';
          file.message = '上传成功';
          this.imgpath = data.data.path;
        })
        .catch((err) => {
          this.imgpath = '';
          file.status = 'failed';
          file.message = '上传失败';
          Toast.fail("系统异常");
          return;
        });

    },
    onOversize(file) {
      Toast.fail(`文件大小不能超过  ${parseInt(this.maxsize / 1024)}KB! `);
    },
  },
  components: {
    Toast,
    Notify
  },
};
</script>

<style lang="scss" scoped>
.headbox {
  margin-top: 46px;
  border-radius: 10px;
  background: url("~@/assets/img/uploadbg.png") no-repeat;
  background-size: cover;
  padding: 10px;
  box-sizing: border-box;
  & .head{
    @include wh(100%,auto);
  }
  & .upbtn {
    @include wh(100%,auto);
    padding: 5px 10px;
    border-radius: 5px;
  }
}
.fontitem{
  border-radius: 2px;
  margin-top: 5px;
  margin-bottom: 5px;
  & textarea {
    white-space:pre;
  }
}
[class*='van-hairline']::after{
  border-color: rgba($color: #79a5df, $alpha: 1.0);
}
.fontOperation{
  position: relative;
    right: -15px;
        width: auto;
    height: auto;
    display: flex;
    flex-direction: column;
}
.wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }

  .block {
    width: 120px;
    height: 120px;
    background-color: #ffffff;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .van-cell{
    overflow: initial;
  }
 ::v-deep .van-field__left-icon{
    position: absolute !important;
    left: -45px !important;
    top: -5px !important;
  }
  ::v-deep .van-button--mini + .van-button--mini {
    margin-left: 0;
    margin-top: 2px
}
.cpmOP{
  display: flex;
  justify-content: space-around;
  @include wh(100%,auto);
  border: 1px solid rgba($color: #bbcfe9, $alpha: 1.0);
  border-radius: 20px;
  padding: 10px 0px;
  background-color: #ffffff;
}


.fonttypepanel{
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-content: space-around;
  & .typescrolllist{
    flex: 0 0 45%;
    overflow-y: scroll;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: flex-start;
    & div{
      flex: 0 1 40%;
      padding: 5px;
      margin: 0px;
      overflow: hidden;
      text-overflow:ellipsis;
      white-space: nowrap;
    }
  }
  
  & .btngroup{
    margin-top: 10px;
  }
  & .img-icon {
    height: 20px;
  }

  
}
</style>